package com.gxy.learn.thread.simple;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * ScheduledExecutorService支持任务调度，持续执行或者延迟一段时间后执行
 * <p>
 * 定时调度线程池demo
 * <p>
 * author: Gao xueyong
 * Create at: 2022/3/20 下午6:12
 */
@Slf4j
public class ScheduledExecutorServicePool {

    public static void main(String[] args) {
//        scheduleTaskDemoOne();
        log.info("now = {}",System.currentTimeMillis());
//        scheduleAtFixedRateTaskDemo();
//        scheduleWithFixedDelayTaskDemo();

    }


    public static void scheduleTaskDemoOne() {
        long start = System.currentTimeMillis();
//        调度一个任务在延迟3分钟后执行
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        Runnable task = () -> {
            long end = System.currentTimeMillis();
            log.info("Scheduling:{}", end);
            log.info("耗时：{}", end - start);
        };
        ScheduledFuture<?> future = executorService.schedule(task, 5, TimeUnit.SECONDS);
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
            log.error("err ", e);
        }
        while (true) {
            long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
            log.info("Remaining Delay: {}", remainingDelay);
            if (remainingDelay <= 0) {
                log.info("task任务被触发！");
                break;
            }
        }
    }

    public static void scheduleAtFixedRateTaskDemo() {
//        任务每秒执行一次
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        Runnable task = () -> {
            log.info("Scheduling:{}", System.currentTimeMillis());
        };
//        每秒执行一次
        executorService.scheduleAtFixedRate(task, 5, 1, TimeUnit.SECONDS);
    }

    public static void scheduleWithFixedDelayTaskDemo() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
//        Runnable task = () -> {
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (Exception e) {
//                log.error("err ", e);
//            }
//
//            log.info("Scheduling:{}", System.currentTimeMillis());
//        };
////        每秒执行一次
//        executorService.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
//        等价于

        Runnable task = () -> {

            log.info("Scheduling:{}", System.currentTimeMillis());
        };
//        每秒执行一次
        executorService.scheduleWithFixedDelay(task, 0, 3, TimeUnit.SECONDS);
    }

}
